//
//  GetLocation.m
//  BrotherMovProject
//
//  Created by zhibao on 2022/1/19.
//

#import "GetLocation.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
static GetLocation *instance = nil;
@interface GetLocation ()<AMapLocationManagerDelegate,AMapSearchDelegate>{
    
}
@property(nonatomic,strong) AMapLocationManager *locationManager;
@property(nonatomic,strong) AMapSearchAPI *search;
@end
@implementation GetLocation
+ (GetLocation *)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[GetLocation alloc] init];
    });
    return instance;
}
-(id)init{
    self = [super init];
    if (self) {
        _model = [LocationModel new];
        self.locationManager = [[AMapLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.search = [[AMapSearchAPI alloc] init];
        self.search.delegate = self;
        
    }
    return self;
}
- (void)getLoctaion{
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为10s
    self.locationManager.locationTimeout =10;
    //   逆地理请求超时时间，最低2s，此处设置为10s
    self.locationManager.reGeocodeTimeout = 10;
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
    __weak typeof(self) weakSelf = self;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == AMapLocationErrorLocateFailed)
            {
                if (self.GetLocationBlock) {
                    self.GetLocationBlock();
                }
                return;
            }
        }
        
        NSLog(@"location:%@", location);
        
        if (regeocode)
        {
            NSLog(@"reGeocode:%@", regeocode);
            NSLog(@"reGeocode:%@", regeocode.citycode);
            AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
            request.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
            request.types = @"商务住宅|地名地址信息|汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|公共设施";
            request.sortrule = 0;
            [self.search AMapPOIAroundSearch: request];
            
            strongSelf.model.formattedAddress = regeocode.formattedAddress;
            strongSelf.model.country = regeocode.country;
            strongSelf.model.province =regeocode.province;
            strongSelf.model.city = regeocode.city;
            strongSelf.model.district = regeocode.district;
            strongSelf.model.citycode = regeocode.citycode;
            strongSelf.model.adcode = regeocode.adcode;
            strongSelf.model.street = regeocode.street;
            strongSelf.model.number = regeocode.number;
            strongSelf.model.POIName = regeocode.POIName;
            strongSelf.model.AOIName = regeocode.AOIName;
            strongSelf.model.lon = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
            strongSelf.model.lat = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
            DLog(@"addresssDic==%@",strongSelf.model.formattedAddress);
        }
    }];
}
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager{
    [locationManager requestAlwaysAuthorization];
}
- (void)onWeatherSearchDone:(AMapWeatherSearchRequest *)request response:(AMapWeatherSearchResponse *)response{
    //解析response获取天气信息，具体解析见 Demo
    NSArray *lives = response.lives;
    if(lives.count > 0){
        AMapLocalWeatherLive *live = lives.firstObject;
        DLog(@"************");
        DLog(@"省份==%@",live.province);
        DLog(@"城市==%@",live.city);
        DLog(@"天气==%@",live.weather);
        DLog(@"温度==%@",live.temperature);
        DLog(@"风向==%@",live.windDirection);
        DLog(@"风力==%@",live.windPower);
        DLog(@"湿度==%@",live.humidity);
        _model.weather = live.weather;
        _model.temperature = live.temperature;
        _model.windDirection = live.windDirection;
        _model.windPower = live.windPower;
        _model.humidity = live.humidity;
        _model.date = [Helper getCurrentTimes:@"yyyy.MM.dd"];
        _model.week = [self getWeekDay:[NSDate new].weekday];
        
        //位置
         NSString *address = [NSString stringWithFormat:@"%@·%@·%@",_model.province,_model.city,_model.name];
        if([_model.province isEqualToString:_model.city]){
            address = [NSString stringWithFormat:@"%@·%@",_model.city,_model.name];
        }
        _model.sjdkdd = address;
        _model.kqdkdd = address;
        _model.wydd = address;
        _model.kddd = address;
        _model.xldd = address;
        _model.rcdd = address;
        _model.jzdd = address;
        _model.fwdd = address;
        _model.wpdwdd = address;
        _model.gadd = address;
        _model.lydd = address;
        
        //天气
        _model.tianqi = [NSString stringWithFormat:@"%@ %@°C %@风(%@级) 湿度%@%@",_model.weather,_model.temperature,_model.windDirection,_model.windPower,_model.humidity,@"%"];
        
        //经纬度
        _model.jw = [NSString stringWithFormat:@"%@°E，%@°N",_model.lon,_model.lat];
        if (self.GetLocationBlock) {
            self.GetLocationBlock();
        }
    }
}
/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }
    AMapPOI *obj = response.pois.firstObject;
    _model.name = obj.name;
    _model.addInfo = obj.address;
    AMapWeatherSearchRequest *wrequest = [[AMapWeatherSearchRequest alloc] init];
    wrequest.city = _model.adcode;
    wrequest.type = AMapWeatherTypeLive; //AMapWeatherTypeLive为实时天气；AMapWeatherTypeForecase为预报天气
    [self.search AMapWeatherSearch:wrequest];
    //    obj.distance;
    __weak typeof(self) weakSelf = self;
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        DLog(@"obj===%@    %@",obj.name,obj.address);
    }];
}
-(NSString *)getWeekDay:(NSInteger)index{
    if(index == 0){
        return LocalizedString(@"星期日");
    }else if(index == 1){
        return LocalizedString(@"星期一");
    }else if(index == 2){
        return LocalizedString(@"星期二");
    }else if(index == 3){
        return LocalizedString(@"星期三");
    }else if(index == 4){
        return LocalizedString(@"星期四");
    }else if(index == 5){
        return LocalizedString(@"星期五");
    }else if(index == 6){
        return LocalizedString(@"星期六");
    }
    return LocalizedString(@"未知");
}
@end
